<template>
  <el-popover v-model:visible="show" popper-class="no-padding-popover"
              placement="bottom" width="240" trigger="click">
    <div class="field-set">
      <el-input v-model="search" class="field-set__search"
                placeholder="搜索字段（拖拽字段进行排序）" @input="searchClick"/>

      <div v-loading="loading" class="field-set__content">
        <!--draggable使用方法-->
        <!--https://gitee.com/haibusoi/vue.draggable.next?_from=gitee_search#features-->
        <!--还剩v-show的逻辑没有处理-->
        <draggable item-key="id" v-model="fields">
          <template v-slot:item="{element}">
            <div>
              <!--            <div v-for="(item, index) in fields" :key="index" v-show="(poolConfig != 1 && item.fieldName !== 'poolDay') || poolConfig == 1"-->
              <div v-show="(poolConfig != 1 && item.fieldName !== 'poolDay') || poolConfig == 1"
                   class="field-set__content--item text-one-line">
                <el-switch v-model="element.check"/>
                <span v-if="element.center">{{ element.left }}<span class="input-word">{{
                    element.center
                  }}</span>{{ element.right }}</span>
                <span v-else>{{ element.name }}</span>
              </div>
            </div>
          </template>
        </draggable>
      </div>

      <div class="field-set__ft">
        <el-button link @click="reSet">重置</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </div>
    <template v-slot:reference>
      <div v-if="$slots.reference" @click="show = !show"/>
      <i v-else class="wk wk-config table-set" @click="show = !show"/>
    </template>

  </el-popover>
</template>

<script setup>
import {
  crmFieldConfigAPIIndexAPI,
  crmPoolFieldConfigIndexAPI,
  crmFieldConfigAPI,
  crmPoolFieldConfigAPI
} from '/src/api/crm/common.js'
import crmTypeModel from '/src/views/crm/model/crmTypeModel.js'
import {objDeepCopy} from '/src/utils/index.js'
import Draggable from 'vuedraggable'
import {ref, watch, onMounted} from "vue"
import {ElMessage} from "element-plus"

/** 字段管理 */
defineOptions({
  name: 'FieldSet',
})

const props = defineProps({
  crmType: String,

  isSeas: {
    type: Boolean,
    default: false
  },

  poolId: [String, Number]
})

const emits = defineEmits([])

const loading = ref(false)
const show = ref(false)
const poolConfig = ref(1) // 1 公海规则打开  0 未打开
const fields = ref([])
// 用于重置
const copyfields = ref([])
const search = ref('')

watch(show, (val) => {
  if (val) {
    getList()
  }
})

watch(() => props.poolId, () => {
  fields.value = []
  if (show.value) {
    getList()
  }
})


onMounted(() => {
  getList()
})


/**
 * 获取数据
 */
function getList() {
  console.log("getListgetList")
  loading.value = fields.value.length == 0
  let request = null
  const params = {}
  if (props.isSeas) {
    request = crmPoolFieldConfigIndexAPI
    params.poolId = props.poolId
  } else {
    request = crmFieldConfigAPIIndexAPI
    params.label = crmTypeModel[props.crmType]
  }

  request(params).then(res => {
    const resData = res.data.data || {}
    poolConfig.value = resData.poolConfig
    const showList = resData.value.map(function (item, index) {
      item.left = ''
      item.center = ''
      item.right = ''
      item.check = true
      return item
    })
    const hideList = resData.hideValue.map(function (item, index) {
      item.left = ''
      item.center = ''
      item.right = ''
      item.check = false
      return item
    })

    fields.value = showList.concat(hideList)
    console.log("fields", fields)
    copyfields.value = objDeepCopy(fields.value)
    loading.value = false
  }).catch(() => {
    console.log("catch", "loading")
    loading.value = false
  })
}

/**
 * 搜索操作
 */
function searchClick() {
  fields.value = fields.value.map(item => {
    const index = item.name.indexOf(search.value)
    if (index != -1) {
      item.left = item.name.substr(0, index)
      item.center = item.name.substr(index, search.value.length)
      const rightIndex = index + search.value.length
      item.right = item.name.substr(rightIndex, item.name.length - rightIndex)
    } else {
      item.left = ''
      item.center = ''
      item.right = ''
    }
    return item
  })
}

/**
 * 保存更改
 */
function save() {
  const noHideFields = fields.value.filter(item => item.check)
  if (noHideFields.length < 2) {
    ElMessage.error({message: '至少要显示两列'})
  } else {
    const hideFields = fields.value.filter(item => !item.check)
    loading.value = true
    let request = null
    const params = {
      noHideFields: noHideFields.map(item => {
        return {
          id: item.id,
          fieldName: item.fieldName,
          style: item.style
        }
      }),
      hideFields: hideFields.map(item => {
        return {
          id: item.id,
          fieldName: item.fieldName,
          style: item.style
        }
      })
    }
    if (props.isSeas) {
      request = crmPoolFieldConfigAPI
      params.poolId = props.poolId
    } else {
      request = crmFieldConfigAPI
      params.label = crmTypeModel[props.crmType]
    }

    request(params).then(res => {
      ElMessage.success({message: '操作成功'})
      show.value = false
      loading.value = false
      emits('change')
    }).catch(() => {
      loading.value = false
    })
  }
}

/**
 * 重置
 */
function reSet() {
  fields.value = objDeepCopy(copyfields.value)
}


</script>


<style lang="scss" scoped>
.field-set {
  &__search {
    padding: 8px 10px 0;
  }

  &__content {
    max-height: 250px;
    min-height: 100px;
    overflow: auto;

    &--item {
      cursor: move;
      padding: 5px 10px;
      font-size: 12px;

      .el-switch {
        transform: scale(0.8);
        margin-right: 3px;

        :deep(.el-switch__core ) {
          width: 33px !important;
        }
      }
    }

    &--item:hover {
      background-color: #E7EDF4;
    }
  }

  &__ft {
    overflow: hidden;
    overflow-y: overlay;
    background-color: $xr--background-color-base;
    padding: 8px 0;
    margin-top: 10px;

    .el-button {
      font-size: 12px;
      float: right;
      padding: 6px 12px;
    }
  }
}

// 设置
.table-set {
  width: 15px;
  margin-top: 5px;
  cursor: pointer;
  color: #9DA9C2;
}

// 搜索到的字
.input-word {
  background-color: $xr-color-primary;
  color: white;
}

.sortable-drag {
  cursor: move;
}
</style>
